package com.falm.picturebackend.aop;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.falm.picturebackend.annotation.AuthCheck;
import com.falm.picturebackend.entity.BO.UserBO;
import com.falm.picturebackend.entity.VO.UserVO;
import com.falm.picturebackend.exception.ErrorCode;
import com.falm.picturebackend.exception.ThrowUtils;
import com.falm.picturebackend.repository.UserRepository;
import com.falm.picturebackend.util.JWTUtil;

/**
 * @author Administrator
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserRepository userRepository;


    @Around(value = "@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        if (StringUtils.isBlank(mustRole)) {
            return joinPoint.proceed();
        }
        // 从RequestContextHolder获取当前请求
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        boolean verifyJwt = JWTUtil.verifyJwt(token);
        ThrowUtils.throwIf(!verifyJwt, ErrorCode.NO_AUTH_ERROR);
        UserVO userVO = JWTUtil.parseJwtGetUserInfo(token);
        UserBO userByUserBOAccount = userRepository.getUserByUserAccount(userVO.getUserAccount());
        ThrowUtils.throwIf(!StringUtils.equals(mustRole, userByUserBOAccount.getUserRole()), ErrorCode.NO_AUTH_ERROR);
        return joinPoint.proceed();
    }

}
